package com.fengwk.support.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.fengwk.support.exception.BaseException;

/**
 * 需要在spring中初始化该bean
 */
@Component
public class SpringBeanUtils implements ApplicationContextAware {  
    
    private static ApplicationContext applicationContext = null;
    
    public SpringBeanUtils() {
    	// should be instance
    }
    
    @Override  
    public void setApplicationContext(ApplicationContext applicationContext) {  
        SpringBeanUtils.applicationContext = applicationContext;  
    }  
    
    public static Object getBeanByName(String beanName) {  
        return getApplicationContext().getBean(beanName);  
    }  
  
    public static <T> T getBean(Class<T> type) {
        return getApplicationContext().getBean(type);
    }
    
    public static Object getBean(String beanName) {
        return getApplicationContext().getBean(beanName);  
    }
    
    public static ApplicationContext getApplicationContext() {
    	if (applicationContext == null){  
    		throw new BaseException("applicationContext is null");
        }
    	return applicationContext;
    }
  
}  